package health.lm.com.component_base.webview;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.LogUtils;
import com.just.agentweb.AgentWeb;
import com.lm.sjy.titlebar.widget.CommonTitleBar;

import butterknife.BindView;
import health.lm.com.component_base.R;
import health.lm.com.component_base.R2;
import health.lm.com.component_base.arouter.Router;
import health.lm.com.component_base.base.mvp.activity.XActivity;
import health.lm.com.component_base.webview.agent.AgentHelper;
import health.lm.com.component_base.webview.sonic.SonicImpl;
import health.lm.com.data.App;

import static com.lm.sjy.titlebar.widget.CommonTitleBar.ACTION_LEFT_BUTTON;

/**
 * 通用的网页展示页面
 */
@Route(path = Router.WebActivity)
public class WebAcitivity extends XActivity implements AgentHelper.ViewClient, AgentHelper.ChromeClient {
    @BindView(R2.id.title_bar)
    protected CommonTitleBar titlebar;
    @BindView(R2.id.linearLayout)
    protected LinearLayout linearLayout;
    protected AgentWeb mAgentWeb;
    protected SonicImpl mSonicImpl;
    @Autowired
    String url = "";


    /**
     * js 调用android 方法
     * 默认是没有的，需要使用的时候复写此方法
     */
    protected void setJsInterface() {
//        mAgentWeb.getJsInterfaceHolder().addJavaObject("",null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mAgentWeb.back()) {
            mAgentWeb.back(); //goBack()表示返回WebView的上一页面
            return true;
        } else {
            finish();
        }
        return false;
    }

    @Override
    protected void onPause() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
        super.onPause();

    }

    @Override
    protected void onResume() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
            LogUtils.e("刷新URL");
            //mAgentWeb.getUrlLoader().reload();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
        if (mSonicImpl != null) {
            mSonicImpl.destrory();
        }
        super.onDestroy();
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {

    }

    /**
     * 获取网页标题
     */
    @Override
    public void onReceivedTitle(WebView view, String title) {

        if (titlebar != null && !TextUtils.isEmpty(title)) {
            if (title.length() > 10) {
                title = title.substring(0, 10).concat("...");
            }
        } else {
            title = getIntent().getStringExtra("title");
        }
        titlebar.getCenterTextView().setText(title);
    }

    /**
     * 加载中的url
     */
    @Override
    public void shouldOverrideUrlLoading(WebView webView, String url) {

    }

    /**
     * 加载开始
     */
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {

    }

    /**
     * 加载结束
     */
    @Override
    public void onPageFinished(WebView view, String url) {

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        String uid = App.getModel().getUid();
        url = getIntent().getStringExtra("url");
        if (url.contains("?")) url = url + "&is_app=1&uid=" + uid;
        else url = url + "?is_app=1&uid=" + uid;
        //url = url + "?is_app=1&uid=" + uid;
        AgentHelper.getInstance().setChromeClient(this);
        AgentHelper.getInstance().setViewClient(this);
        // 1. 首先创建SonicImpl
        mSonicImpl = new SonicImpl(url, this);
        // 2. 调用 onCreateSession
        mSonicImpl.onCreateSession();
        //3. 创建AgentWeb ,加入SonicWebViewClient中间件
        mAgentWeb = AgentHelper.getInstance().getAgentWeb(this, linearLayout, mSonicImpl, url);
        //4. 注入 JavaScriptInterface
        setJsInterface();
        //5. 最后绑定AgentWeb
        mSonicImpl.bindAgentWeb(mAgentWeb);
        //返回键
        titlebar.setListener((v, action, extra) -> {
            if (action == ACTION_LEFT_BUTTON) {
                if (!mAgentWeb.back()) {
                    finish();
                }
            }
        });
        WebSettings settings = mAgentWeb.getWebCreator().getWebView().getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setTextZoom(100);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_web;
    }

    @Override
    public Object newP() {
        return null;
    }
}
